package com.tencent.sr.iris.activity.service.event.activity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityCheckResultDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityTaskDTO;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityIdEnum;
import com.tencent.sr.iris.activity.interfaces.event.dto.ActivityEventDTO;
import com.tencent.sr.iris.activity.service.activity.IrisUserActivityRecordService;
import com.tencent.sr.iris.activity.service.activity.IrisUserTaskRecordService;
import com.tencent.sr.iris.activity.service.event.task.IrisTaskExecutor;
import com.tencent.sr.iris.user.core.service.interfaces.enums.UserLevelEnum;
import com.tencent.sr.iris.user.core.service.interfaces.request.message.UserActivityLevelUpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * Copyright (C) 2023 Limited, a Tencent company. All rights reserved.
 * 辅导津贴活动执行器
 *
 * @author p_htaozhou@tencent.com
 * @create 2023/8/17 15:11
 */

@Slf4j
@Component
public class GuideAllowanceActivityExecutor extends AbstractIrisActivityExecutor {

    @Resource
    private IrisUserActivityRecordService irisUserActivityRecordService;

    @Resource
    private IrisUserTaskRecordService userTaskRecordService;

    @Override
    protected void process(ActivityEventDTO msg, ActivityDTO activity, List<String> eventHandingInfoList) {
        log.info("【辅导津贴活动执行器】开始执行");
        // 1、活动基础校验
        ActivityCheckResultDTO activityFlag = doActivityCheck(activity, msg);
        if (!activityFlag.isSatisfy()) {
            log.info("【辅导津贴活动执行器】不满足辅导津贴活动准入规则,activityId={},errorMsg:{},msg={}", activity.getBizId(), activityFlag.getErrorMsg(),
                    JSONObject.toJSONString(msg));
            eventHandingInfoList.add("【辅导津贴活动执行器】不满足辅导津贴活动准入规则,errorMsg=" + activityFlag.getErrorMsg());
            return;
        }

        // 2、活动准入规则校验，不满足则删除进行中的任务记录
        ActivityCheckResultDTO accessConditionCheckResult = doAccessConditionCheck(activity, msg);
        if (!accessConditionCheckResult.isSatisfy()) {
            log.info("【辅导津贴活动执行器】不满足活动准入规则,activityId={},errorMsg:{}, msg={}", activity.getBizId(),
                    accessConditionCheckResult.getErrorMsg(),
                    JSONObject.toJSONString(msg));
            eventHandingInfoList.add("【辅导津贴活动执行器】不满足活动准入规则,errorMsg=" + accessConditionCheckResult.getErrorMsg());
            //如果不满足活动任务门槛，删除已存在的进行中任务记录
            int i = userTaskRecordService.deleteInProgressTaskRecord(msg.getUid(), activity.getBizId(), null);
            eventHandingInfoList.add("【辅导津贴活动执行器】删除进行中的任务记录,result:" + i + "条");
            activityRecordService.handleInProgressActivityRecord(msg.getUid(), activity.getBizId());
            return;
        }

        // 3、执行任务执行器
        activity.getActivityTaskDTOS().forEach(t -> {
            // 获取任务执行器
            IrisTaskExecutor taskExecutor = getTaskExecutor(msg, activity, t);
            log.info("【辅导津贴活动执行器】获取任务执行器成功：{}", taskExecutor.getClass().getSimpleName());
            taskExecutor.execute(msg, activity, t, null);
        });

        // 4、更新活动记录表
        activityRecordService.addOrUpdateActivityRecord(msg.getUid(), msg.getEventTime(), activity.getBizId(),
                activity.getPeriodType(), activity.getPeriod());
        log.info("【辅导津贴活动执行器】执行结束");
    }

    @Override
    protected void after(ActivityEventDTO eventDTO, ActivityDTO act) {

    }

    @Override
    protected List<ActivityTaskDTO> getTask(ActivityEventDTO eventDTO, ActivityDTO act) {
        return null;
    }

    @Override
    protected void check(ActivityEventDTO eventDTO, ActivityDTO act) {
    }

    @Override
    public ActivityCheckResultDTO doActivityCheck(ActivityDTO activity, ActivityEventDTO msg) {
        // 活动时间校验
        Long eventTime = msg.getEventTime();
        if (activity.getStartTime().getTime() > eventTime || eventTime > activity.getEndTime().getTime()) {
            log.info("【辅导津贴活动执行器】超出活动时间范围,eventTime={},activityStartTime={},activityEndTime={}", eventTime,
                    activity.getStartTime().getTime(),
                    activity.getEndTime().getTime());
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg("超出活动时间范围").build();
        }

        return ActivityCheckResultDTO.builder().satisfy(true).build();
    }

    @Override
    public ActivityCheckResultDTO doAccessConditionCheck(ActivityDTO activity, ActivityEventDTO msg) {
        String eventInfo = msg.getEventInfo();
        UserActivityLevelUpRequest levelUpRequest = JSON.parseObject(eventInfo, UserActivityLevelUpRequest.class);
        String afterLevelId = levelUpRequest.getAfterLevelId();
        String uid = levelUpRequest.getUid();

        // 校验是否存在上级
        if (!StringUtils.hasText(msg.getPid())) {
            String errorMsg = String.format("【辅导津贴活动执行器】用户(%s)上级为空。", afterLevelId);
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg(errorMsg).build();
        }

        // 校验用户升级后是否为超级会员
        if (!Objects.equals(UserLevelEnum.SUPER.getValue(), afterLevelId)) {
            String errorMsg = String.format("【辅导津贴活动执行器】用户(%s)升级后等级为：%s，不为超级会员。", uid, afterLevelId);
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg(errorMsg).build();
        }

        // 校验是否已完成过辅导津贴
        if (irisUserActivityRecordService.existActivityRecord(
                uid, ActivityIdEnum.GUIDE_ALLOWANCE.getCode(), null)) {
            String errorMsg = String.format("【辅导津贴活动执行器】用户(%s)已完成过辅导津贴活动。", uid);
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg(errorMsg).build();
        }

        return ActivityCheckResultDTO.builder().satisfy(true).build();
    }
}
